<template>
  <div class="chart-container">
    <div ref="chartRef" class="temperature-chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const chartRef = ref(null);
let chart = null;

// 图表配置项
const option = {
  title: {
    text: '实时温度监控',
    left: 'center',
    textStyle: {
      color: '#333',
      fontSize: 20
    }
  },
  tooltip: {
    trigger: 'axis',
    formatter: function(params) {
      const time = params[0].axisValue;
      const temp = params[0].data;
      return `时间：${time}<br/>温度：${temp}°C`;
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    axisLabel: {
      rotate: 45,
      interval: 'auto'
    }
  },
  yAxis: {
    type: 'value',
    name: '温度(°C)',
    axisLabel: {
      formatter: '{value} °C'
    }
  },
  series: [{
    name: '温度',
    type: 'line',
    smooth: true,
    data: [],
    itemStyle: {
      color: '#409EFF'
    },
    areaStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        {
          offset: 0,
          color: 'rgba(64, 158, 255, 0.5)'
        },
        {
          offset: 1,
          color: 'rgba(64, 158, 255, 0.1)'
        }
      ])
    }
  }]
};

// 获取数据的函数
const fetchData = async () => {
  try {
    const response = await fetch('https://penglink.pcwxcn.top/api/dashboard/temperature/chart');
    const result = await response.json();
    
    if (result.code === 200) {
      const { times, temperatures } = result.data;
      
      // 更新图表数据
      option.xAxis.data = times;
      option.series[0].data = temperatures;
      
      if (chart) {
        chart.setOption(option);
      }
    }
  } catch (error) {
    console.error('获取温度数据失败:', error);
  }
};

// 定时器引用
let timer = null;

onMounted(() => {
  // 初始化图表
  chart = echarts.init(chartRef.value);
  chart.setOption(option);
  
  // 首次加载数据
  fetchData();
  
  // 设置定时刷新
  timer = setInterval(fetchData, 60000); // 每分钟刷新一次
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chart?.resize();
  });
});

onUnmounted(() => {
  // 清理定时器和图表实例
  if (timer) {
    clearInterval(timer);
  }
  if (chart) {
    chart.dispose();
    chart = null;
  }
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.temperature-chart {
  width: 100%;
  height: 500px;
}
</style> 